import json
import os

from devicetest.api import print_info, Asserts
from devicetest.aw.OpenHarmony import CommonOH
from devicetest.core.test_case import TestCase, Step

from aw.common import common_setup, common_teardown, crop_picture, compare_image_similarity
from aw.pom import DeskTop, Setting


class PreTest_RK3568_Basic_Desktop_0300(TestCase, DeskTop):
    # 预置条件：
    # 烧写目标版本后，正常进入桌面
    # 测试步骤：
    # 长按桌面空白处，点击更多设置，开启手势导航开关
    # 预期结果：
    # 开启后底部导航栏消失，可上滑进入recent页面，左右往里滑动返回

    def __init__(self, controllers):
        self.TAG = self.__class__.__name__
        TestCase.__init__(self, self.TAG, controllers)
        self.screenshot_dir = os.path.join(self.cur_case.case_screenshot_dir, self.cur_case.name)
        self.resource_dir = os.path.join(os.path.dirname(self.configs['testcases_path']), 'resource')

        self.standard_gesture_pic = os.path.join(self.resource_dir, 'desktop', 'nb_gesture.jpeg')

    def setup(self):
        common_setup(self.Phone1)

    def process(self):
        Step('步骤1、长按桌面空白处，点击更多设置，开启手势导航开关')
        CommonOH.click(self.Phone1, **self.center, mode='LONG')
        CommonOH.touchByText(self.Phone1, '更多设置')
        property_dict = json.loads(CommonOH.getWidgetProperties(self.Phone1, condition='type/Toggle'))
        switch_status = property_dict.get('checked')
        if not switch_status:
            CommonOH.touchByType(self.Phone1, 'Toggle')
        CommonOH.goBack(self.Phone1, mode='GESTURE')
        Step('预期结果1、开启后底部导航栏消失，可上滑进入recent页面，左右往里滑动返回')
        gesture_pic = os.path.join(self.screenshot_dir, '{}_gesture.jpeg'.format(self.Phone1.device_sn))
        CommonOH.takePicture(self.Phone1, gesture_pic)
        crop_picture(gesture_pic, **self.navigation_bar)
        similarity = compare_image_similarity(gesture_pic, self.standard_gesture_pic)
        print_info('预期结果2.相似度为：{}'.format(similarity))
        Asserts.assert_greater(similarity, 0.5)
        CommonOH.wait(self.Phone1, 1)
        CommonOH.startAbility(self.Phone1, Setting.ability_name, Setting.bundle_name)
        CommonOH.wait(self.Phone1, 0.5)
        CommonOH.touchByText(self.Phone1, 'WLAN')
        CommonOH.goBack(self.Phone1, mode='GESTURE')
        CommonOH.checkIfTextExist(self.Phone1, '设置')
        CommonOH.goHome(self.Phone1, mode='GESTURE')
        CommonOH.touchRecentKey(self.Phone1, mode='GESTURE')
        CommonOH.checkIfTextExist(self.Phone1, '设置')
        CommonOH.goHome(self.Phone1, mode='GESTURE')

    def teardown(self):
        Step('收尾动作0：重新禁用手势导航')
        CommonOH.click(self.Phone1, **self.center, mode='LONG')
        CommonOH.touchByText(self.Phone1, '更多设置')
        property_dict = json.loads(CommonOH.getWidgetProperties(self.Phone1, condition='type/Toggle'))
        switch_status = property_dict.get('checked')
        if switch_status:
            CommonOH.touchByType(self.Phone1, 'Toggle')
        common_teardown(self.Phone1)
